package org.example.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UDTF2
 * @Author 小坏
 * @Date 2021/9/24、20:12
 * @Version 1.0
 *
 *
 * 输入数据：hello,atguigu:hello,hive
 *
 * 输出数据
 *
 * hello atguigu
 *
 * hello hive
 */
public class MyUDTF2 extends GenericUDTF {
    //输出数据的集合
    private ArrayList<String> outPutList = new ArrayList<>();
    /**
     * 初始化方法
     * 炸裂出来多个列、所以是集合
     *
     * @param argOIs
     * @return
     * @throws UDFArgumentException
     */
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //输出数据的默认列名、可以别名覆盖
        //两个列
        List<String> fieldNames = new ArrayList<>();
        fieldNames.add("word1");
        fieldNames.add("word2");

        //输出数据的类型
        List<ObjectInspector> fieldOIs = new ArrayList<>();

        //类型校验器两个
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        //最终返回值
        return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
    }


    @Override
    public void process(Object[] args) throws HiveException {
        //取出输入数据
        String input = args[0].toString();

        //按照，分割字符串  输入数据：hello,atguigu:hello,hive  冒号分隔
        String[] fields = input.split(":");

        for (String field : fields) {
            //清空集合
            outPutList.clear();

            //将field按照，分割
            String[] words = field.split(",");
            outPutList.add(words[0]);
            outPutList.add(words[1]);

            //写出数据
            forward(outPutList);
        }

        //遍历数据写出

    }

    @Override
    public void close() throws HiveException {

    }
}
